package com.xci.core.handler;

import com.xci.core.helper.FileHelper;
import com.xci.core.handler.FreemarkerViewHandlerInterceptor;
import com.xci.core.internal.ApiInterceptor;
import com.xci.core.internal.RequestJsonHandlerMethodArgumentResolver;
import com.xci.core.internal.WebInterceptor;
import com.xci.core.setting.ApiSetting;
import com.xci.core.setting.UploadSetting;
import com.xci.core.setting.WebSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * SpringMVC配置
 *
 * @author 吕艳阳
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Resource
    private ApiSetting apiSetting;
    @Resource
    private WebSetting webSetting;
    @Resource
    private ApiInterceptor apiInterceptor;
    @Resource
    private WebInterceptor webInterceptor;
    @Resource
    private FreemarkerViewHandlerInterceptor freemarkerViewHandlerInterceptor;
    @Resource
    private UploadSetting uploadSetting;

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 拦截api权限判断
        registry.addInterceptor(apiInterceptor)
                .addPathPatterns(apiSetting.getUrlPatterns())
                .excludePathPatterns(apiSetting.getExcludes());

        // 拦截所有请求判断Web权限
        registry.addInterceptor(webInterceptor)
                .addPathPatterns(webSetting.getAuthUrlPatterns())
                .excludePathPatterns(webSetting.getAuthExcludes());//不拦截

        // 所有页面注入工具类变量
        registry.addInterceptor(freemarkerViewHandlerInterceptor)
                .addPathPatterns(webSetting.getAuthUrlPatterns())
                .excludePathPatterns(webSetting.getAuthExcludes());//不拦截
    }

    /**
     * 配置静态资源访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        var upgradePath = FileHelper.buildRootFilePath(uploadSetting.buildPath("/upgrade/"));
        registry.addResourceHandler("/upgrade/**").addResourceLocations("file:" + upgradePath);
        // registry.addResourceHandler("/uploads/**").addResourceLocations("file:" + FileHelper.buildRootFilePath("/uploads/"));

        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    // //使用阿里 FastJson 作为JSON MessageConverter
    // @Override
    // public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //     FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    //     FastJsonConfig config = new FastJsonConfig();
    //     config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,//保留空的字段
    //             SerializerFeature.WriteNullStringAsEmpty,//String null -> ""
    //             SerializerFeature.WriteNullNumberAsZero);//Number null -> 0
    //     converter.setFastJsonConfig(config);
    //     converter.setDefaultCharset(Charset.forName("UTF-8"));
    //     converters.add(converter);
    // }

    // /**
    //  * 以前要访问一个页面需要先创建个Controller控制类，再写方法跳转到页面 在这里配置后就不需要那么麻烦了，直接访问http://localhost:8080/toLogin就跳转到login.jsp页面了
    //  */
    // @Override
    // public void addViewControllers(ViewControllerRegistry registry) {
    //     //registry.addViewController("/toLogin").setViewName("login");
    // }


    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(createRequestJsonHandlerMethodArgumentResolver());
    }

    @Bean("requestJsonHandlerMethodArgumentResolver")
    public RequestJsonHandlerMethodArgumentResolver createRequestJsonHandlerMethodArgumentResolver() {
        return new RequestJsonHandlerMethodArgumentResolver();
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        return new StringHttpMessageConverter(StandardCharsets.UTF_8);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
    }
}